<template>
  <div class="booking-status">
    <div class="header">
      <el-button @click="goBack">返回</el-button>
      <span class="venue-name">{{ venueInfo.name }}</span>
      <el-date-picker
        v-model="selectedDate"
        type="date"
        placeholder="选择日期"
        :disabled-date="disabledDate"
        style="margin-left: 20px;"
        @change="fetchBookingStatus"
      />
    </div>
    
    <!-- 统计概览 -->
    <el-card class="summary-card" v-if="dailySummary">
      <div class="summary-stats">
        <div class="stat-item">
          <div class="stat-value">{{ dailySummary.total_booked }}</div>
          <div class="stat-label">总预订人数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ dailySummary.total_attended }}</div>
          <div class="stat-label">总到场人数</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ dailySummary.total_capacity }}</div>
          <div class="stat-label">总容量</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ dailySummary.average_occupancy_rate }}%</div>
          <div class="stat-label">平均预订率</div>
              </div>
            </div>
    </el-card>

    <!-- 时段卡片 -->
    <div class="time-slots-container">
      <div 
        v-for="slot in timeSlots" 
        :key="slot.time_slot_id" 
        class="time-slot-card"
        :class="{ 'fully-booked': slot.available_spots <= 0 }"
      >
        <div class="slot-header">
          <div class="time-range">{{ slot.time_range }}</div>
          <div class="per-person-price">¥{{ slot.per_person_price }}/人</div>
        </div>
        
        <div class="slot-capacity">
          <span class="capacity-text">容量: {{ slot.capacity }}人</span>
        </div>
        
        <div class="slot-stats">
          <div class="stat-row">
            <span class="stat-label">预订人数:</span>
            <span class="stat-value booked">{{ slot.booked_count }}人</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">到场人数:</span>
            <span class="stat-value attended">{{ slot.attended_count }}人</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">剩余名额:</span>
            <span class="stat-value available">{{ slot.available_spots }}人</span>
          </div>
        </div>
        
        <div class="slot-rates">
          <el-tag :type="slot.occupancy_rate > 80 ? 'danger' : slot.occupancy_rate > 50 ? 'warning' : 'success'" size="small">
            预订率: {{ slot.occupancy_rate }}%
          </el-tag>
          <el-tag v-if="slot.booked_count > 0" :type="slot.attendance_rate > 80 ? 'success' : 'info'" size="small" style="margin-left: 5px;">
            到场率: {{ slot.attendance_rate }}%
          </el-tag>
        </div>
        
        <div class="slot-actions">
          <el-button size="small" type="primary" @click="manageSlot(slot)">
            设置
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import request from '@/utils/request'
import { ElMessage } from 'element-plus'

export default {
  name: 'BookingStatus',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const venueId = route.params.id
    const venueInfo = reactive({})
    const selectedDate = ref(new Date())
    const timeSlots = ref([])
    const dailySummary = ref(null)
    const isLoading = ref(false)

    // 允许选择所有日期（包括未来日期）
    const disabledDate = (date) => {
      return false
    }

    // 获取场馆信息
    const fetchVenueInfo = async () => {
      try {
        const res = await request.get(`/v1/admin/venues/${venueId}`)
        Object.assign(venueInfo, res.data)
      } catch (e) {
        ElMessage.error('获取场馆信息失败')
      }
    }

    // 获取预订统计数据
    const fetchBookingStatus = async () => {
      // 防止重复调用
      if (isLoading.value) {
        console.log('API正在调用中，跳过重复请求')
        return
      }
      
      isLoading.value = true
      try {
        const dateStr = selectedDate.value instanceof Date
          ? selectedDate.value.toISOString().slice(0, 10)
          : selectedDate.value
        
        console.log('=== 调试信息 ===')
        console.log('选择的日期:', dateStr)
        console.log('场馆ID:', venueId)
        console.log('请求URL:', `/v1/admin/venues/${venueId}/booking-statistics?date=${dateStr}`)
        console.log('Token:', localStorage.getItem('admin_token'))
        
        const res = await request.get(`/v1/admin/venues/${venueId}/booking-statistics`, {
          params: { date: dateStr }
        })
        
        console.log('API响应:', res)
        
        if (res.data && res.data.hourly_stats) {
          console.log('预订统计数据:', res.data.hourly_stats)
          console.log('日汇总数据:', res.data.daily_summary)
          timeSlots.value = res.data.hourly_stats
          dailySummary.value = res.data.daily_summary
          Object.assign(venueInfo, res.data.venue_info)
        } else {
          console.log('没有找到预订统计数据')
          timeSlots.value = []
          dailySummary.value = null
        }
      } catch (e) {
        console.error('获取预订统计失败:', e)
        ElMessage.error('获取预订统计失败')
        timeSlots.value = []
        dailySummary.value = null
      } finally {
        isLoading.value = false
      }
    }

    // 管理时段
    const manageSlot = (slot) => {
      // 这里可以跳转到时段管理页面或打开管理对话框
      ElMessage.info(`管理时段: ${slot.time_range}`)
    }

    const goBack = () => {
      router.push('/venue/list')
    }

    onMounted(async () => {
      await fetchVenueInfo()
      // 初始化时调用一次，后续只在日期变化时调用
      await fetchBookingStatus()
    })

    return {
      venueInfo,
      selectedDate,
      timeSlots,
      dailySummary,
      disabledDate,
      fetchBookingStatus,
      manageSlot,
      goBack
    }
  }
}
</script>

<style scoped>
.booking-status {
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.venue-name {
  font-size: 18px;
  font-weight: bold;
  margin-left: 20px;
}

.summary-card {
  margin-bottom: 20px;
}

.summary-stats {
  display: flex;
  justify-content: space-around;
  text-align: center;
}

.stat-item {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.time-slots-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.time-slot-card {
  border: 1px solid #EBEEF5;
  border-radius: 8px;
  padding: 16px;
  background: white;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.time-slot-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  transform: translateY(-2px);
}

.time-slot-card.fully-booked {
  border-color: #F56C6C;
  background: #FEF0F0;
}

.slot-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #EBEEF5;
}

.time-range {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.per-person-price {
  font-size: 14px;
  color: #409EFF;
  font-weight: bold;
}

.slot-capacity {
  margin-bottom: 12px;
}

.capacity-text {
  font-size: 14px;
  color: #606266;
}

.slot-stats {
  margin-bottom: 12px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.stat-row .stat-label {
  font-size: 14px;
  color: #606266;
}

.stat-row .stat-value {
  font-size: 14px;
  font-weight: bold;
}

.stat-value.booked {
  color: #E6A23C;
}

.stat-value.attended {
  color: #67C23A;
}

.stat-value.available {
  color: #409EFF;
}

.slot-rates {
  margin-bottom: 12px;
}

.slot-actions {
  text-align: right;
}
</style> 